<template>
	<view style="width: 100%;height: 100%;position: relative;">
		<!-- 顶部安全距离 -->
		<view :style="{height: sConf.tH+'px'}"></view>
		<swiper :duration="500" style="height: 100vh;" @change="swiperEvent">
			<swiper-item v-for="(item,index) in allLevel" :key="index">
				<subLevelCardVue :level="item" :staff="curStaff" @upLevel="upLevelFunc"></subLevelCardVue>
			</swiper-item>
		</swiper>
		<view class="indication">
			<block v-for="(item,index) in allLevel.length" :key="index">
				<view class="spot" :class="curSwiper==index?'active':''"></view>
			</block>
		</view>
		<!-- 顶部自定义导航 -->
		<tn-navbar :placeholder="true" fixed text-color="#70552d">{{sConf.title}} • {{title}}</tn-navbar>

		<!-- popup模态窗口 -->
		<tn-popup v-model="showPopup" open-direction="bottom">
			<view class="gl-pop-page">
				<view class="" style="display: flex;gap: 10px;">
					<view class="" style="padding: 5px;background-color: #00000033;border-radius: 10px;">
						<tn-icon :name="sConf.pics + (curLevel?.icon || '/media/default/default.png')"
							size="128"></tn-icon>
					</view>
					<view class="" style="display: flex;flex-direction: column;justify-content: space-around;">
						<text style="font-size: large;font-weight: bold;">{{curLevel?.name}}</text>
						<view style="font-size: larger;display: flex;align-items: flex-end;"> ￥<view class="buy-price"
								style="color: #ff6b6b;">{{(curPrice/100).toFixed(2)}}</view>
						</view>
					</view>
				</view>

				<scroll-view v-if="curLevel?.level == 2" scroll-y="true" style="max-height: 35vh;">
					<view class=""
						style="margin: 5px 0;padding: 5px; background-color: bisque;color: #ff6b6b;border-radius: 5px;">
						加入会员享超值换购
					</view>
					<tn-radio-group v-model="curProduct" @change="productChange">
						<view v-for="(item, index) in vipGoods" :key="index" @click="productChangeManual(item.id)"
							style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 5px;width: 100%;">
							<view style="display: flex;gap: 10px;">
								<image :src="sConf.pics + (item.face || '/media/default/cover.png')" mode="aspectFill"
									style="width: 64px;height: 64px;padding: 2px;background-color: #00000033;border-radius: 5px;">
								</image>
								<view style="display: flex;flex-direction: column;justify-content: space-around;">
									<view style="font-size: large;font-weight: bold;color: #000000aa;">{{item.name}}
									</view>
									<view style="font-size: larger;display: flex;align-items: flex-end;">￥ <view
											class="buy-price" style="color: #ff6b6b;">
											{{(item.cur_card/100).toFixed(2)}}
										</view>
									</view>
								</view>
							</view>
							<view class=""><tn-radio :label="item.id"></tn-radio></view>
						</view>
					</tn-radio-group>
				</scroll-view>

				<!-- 收货地址 -->
				<view v-if="curLevel?.level == 2" style="padding: 10px;display: flex;justify-content:space-between;"
					:class="warn ? 'warn-address' : ''" @tap="addressChange">
					<view style="font-weight: bold;"> 地址 </view>
					<view v-if="curAddress">
						<view> {{ zipStr(curAddress?.name) }} {{ zipStr(curAddress?.phone) }}</view>
						<view>{{ curAddress?.sheng }} {{ curAddress?.shi }} {{ curAddress?.xian }}
							{{ curAddress?.zhen }}
						</view>
						<view> {{ curAddress?.address }}</view>
					</view>
					<view v-else>
						<text style="color: #aaa;">请选择收货地址</text>
					</view>
				</view>

				<!-- 支付方式 -->
				<view style="padding: 10px;display: flex;justify-content:space-between;align-items: center; "
					@tap="paymentChange">
					<view style="font-weight: bold;"> 支付方式 </view>
					<view style="display: flex;align-items: center;gap: 5px;">
						<tn-icon :name="curPayMent?.icon" :color="curPayMent?.color" size="64"></tn-icon>
						<text>{{ curPayMent?.text }}</text>
					</view>
				</view>

				<!-- 备注 -->
				<view style="padding: 10px;border-radius: 10px;display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 备注 </view>
					<view style="color: #aaa;" @click="showNodeBlock">{{ nodeData ?? '无备注' }} ></view>
				</view>


				<!-- 支付按钮 -->
				<button style="background-color: #000;color:#fff;margin-top: 20px;" @click="reqsnChange">提交订单</button>

				<!-- 选择收货地址 -->
				<tn-action-sheet ref="actionSheetRef"></tn-action-sheet>
				<!-- 填写备注 -->
				<tn-popup v-model="showNode" open-direction="bottom">
					<view class="tn-p-lg" style="background-color: #fff;padding: 10px;">
						<view style="font-weight: bold;"> 备注 </view>
						<textarea :value="nodeData ?? ''" placeholder-style="color:#aaa" maxlength="255"
							@input="conformNode" placeholder="选填,建议先与商家协商一致"
							style="background-color: #f1f1f1;width: 100%;height: 18vh;padding: 10px;border-radius: 10px;margin-top: 10px;"></textarea>
						<view class="toSubmitReqsn"
							style="border-radius: 10px;margin-top:10px;padding: 10px;display: flex;justify-content: center;color: #fff;"
							@click="showNodeBlock">
							<view class=""> 提交 </view>
						</view>
					</view>
				</tn-popup>

			</view>
		</tn-popup>


	</view>
</template>

<script>
	import utils from '@/common/utils';
	import psMethod from '@/common/psMethod';
	import subSecretCardVue from '@/components/sub-secret-card/sub-secret-card.vue';
	import subLevelCardVue from './sub-level-card.vue';
	export default {
		data() {
			return {
				title: '会员权益',
				sConf: getApp().globalData,
				curStaff: null,
				curSwiper: 0,
				allLevel: [],
				vipGoods: [],
				showPopup: false,
				curPrice: 0, // 当前价格
				curLevel: null, // curLevel需要升级的权益				
				curProduct: null, // 当前产品
				curAddress: null,
				curPayMent: {
					text: '微信支付',
					value: 'wxpay',
					icon: 'payment-wechat',
					color: '#48AC35'
				},
				nodeData: null,
				warn: false,
				showNode: false,


			}
		},
		onLoad() {
			this.loadDefData()
		},
		components: {
			subSecretCardVue,
			subLevelCardVue
		},
		methods: {

			zipStr(e) {
				return utils.zipStr(e)
			},
			filterLevel(e) {
				return this.allLevel.find(item => item.level === e)
			},
			filterProduct(e) {
				return this.vipGoods.find(item => item.id === e)
			},
			swiperEvent(e) {
				console.log('swiperEvent', e.detail.current);
				this.curSwiper = e.detail.current
			},
			conformNode(e) {
				console.log('conformNode');
				this.nodeData = e.detail.value
			},
			showNodeBlock() {
				console.log('showNodeBlock');
				this.showNode = !this.showNode
			},
			productChange(e) {
				console.log('productChange', e, this.curProduct);
				this.curPrice = this.curLevel.money + this.filterProduct(e).cur_card
			},
			productChangeManual(e) {
				console.log('productChangeManual', e);
				this.curProduct = e
				this.curPrice = this.curLevel.money + this.filterProduct(e).cur_card
			},
			paymentChange() {
				console.log('paymentChange');
				let that = this
				this.$refs.actionSheetRef.show({
					actions: [{
						text: '微信支付',
						value: 'wxpay',
						icon: 'payment-wechat',
						color: '#48AC35'
					}],
					title: '选择支付方式',
					cancel() {
						return true
					},
					select(index, value) {
						console.log('选项被点击', index, value)
						that.curPayMent = {
							text: '微信支付',
							value: 'wxpay',
							icon: 'payment-wechat',
							color: '#48AC35'
						}
						return true
					}
				})
			},
			async addressChange() {
				console.log('addressChange');
				let addressData = await this.loadStaffAddress()
				let tmpData = []
				addressData.forEach(item => {
					tmpData.push({
						value: item.id,
						text: this.zipStr(item.name) + ' ' + this.zipStr(item.phone),
						desc: item.address
					})
					console.log('转换数据.');
				})


				if (tmpData.length === 0) {
					uni.navigateTo({
						url: '/pageb/userinfo/address'
					})
				}

				let that = this
				this.$refs.actionSheetRef.show({
					actions: tmpData,
					title: '请选择收货信息',
					cancel: () => {
						return true
					},
					select: (index, value) => {
						console.log('选项被点击', index, value)
						that.curAddress = addressData.find(item => item.id === value)
						that.warn = false
						return true
					}
				})

			},
			async upLevelFunc(e) {
				console.log('upLevelFunc', e);
				if (e === 2) {
					let good = await this.loadPayBuyVipList()
					this.vipGoods = good
				}
				this.curLevel = this.filterLevel(e)
				this.curPrice = this.curLevel.money
				this.showPopup = !this.showPopup
			},
			async loadDefData() {
				let level = await this.loadDataLevel()
				this.allLevel = level
				let staff = await this.loadDataUser()
				this.curStaff = staff


				// this.avatarUrl = 'https://cos.yuejunxi.com' + staff.face
				// this.avatarNam = staff.nicename

				// if (this.avatarNam === '新用户' || this.avatarUrl.includes('default/default') || staff.phone === null) {
				// 	console.log('需要改昵称');
				// 	this.$refs.showVerify.open()
				// }
			},
			/**
			 * 加载用户收货地址
			 */
			loadStaffAddress() {
				let host = this.sConf.host + '/weapps/address/';
				let token = this.sConf.token || '';
				let data = {
					sid: this.sConf.auth.id
				}
				return new Promise((resolve, reject) => {
					psMethod.authenticatorGetSync(host, token, data).then(res => {
						console.log('加载收货地址', res);
						resolve(res.resmsg)
					}).catch(err => {
						reject(err)
					})
				})
			},
			/**
			 * 加载升级会员产品
			 */
			loadPayBuyVipList() {
				let host = this.sConf.host + '/weapps/product/'
				let token = this.sConf.token || ''
				let data = {
					is_card: 1,
					is_list: 1,
					status: 1
				}
				return new Promise((resolve, reject) => {
					psMethod.authenticatorGetSync(host, token, data).then(res => {
						console.log('加载升级会员产品', res);
						resolve(res.resmsg)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadDataUser() {
				let host = this.sConf.host + '/weapps/userinfo/' + this.sConf.auth.id + '/'
				let token = this.sConf.token
				return new Promise((resolve, reject) => {
					psMethod.authenticatorGetSync(host, token, {}).then(res => {
						console.log('加载个人信息', res);
						resolve(res.resmsg)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadDataLevel() {
				let host = this.sConf.host + '/weapps/staffLevel/'
				let token = this.sConf.token
				let data = {
					status: 1,
					is_show: 1,
					ordering: 'id'
				}
				return new Promise((resolve, reject) => {
					psMethod.authenticatorGetSync(host, token, data).then(res => {
						console.log('加载权益等级', res);
						resolve(res.resmsg)
					}).catch(err => {
						reject(err)
					})
				})
			},
			reqsnChange() {
				console.log('提交订单');
				if (!this.curStaff.parent) {
					uni.showModal({
						title: '失败',
						content: '您尚未加入任何团队',
						showCancel: false
					})
					return
				}
				if (this.curLevel.level === 2) {
					if (!this.curProduct || !this.curAddress) {
						uni.showModal({
							title: '失败',
							content: '请选择换购商品或收货地址',
							showCancel: false
						})
						return
					}
				}

				let that = this
				uni.showModal({
					title: '微信支付',
					content: '是否确认要支付 ' + (that.curPrice / 100).toFixed(2) + '元',
					success(r) {
						if (r.confirm) {
							let host = that.sConf.host + '/weapps/payLevel/';
							let token = that.sConf.token || '';
							let data = {
								level: that.curLevel.level
							}
							if (that.curLevel.level === 2) {
								data.cge = that.curProduct
								data.ads = that.curAddress.id
							}
							console.log('请求参数', data);
							psMethod.authenticatorPostSync(host, token, data).then(res => {
								console.log('支付升级会员', res.resmsg);
								utils.requestPaymentSync(res.resmsg[0]).then(r => {
									console.log('支付成功', r);
								}).catch(e => {
									console.log('支付失败', e);
								}).finally(() => {
									uni.redirectTo({
										url: '/pageb/reqsn/paystate?reqsn=' + res.resmsg[1]
									})
								})
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 轮播指示点 start*/
	.indication {
		z-index: 9999;
		width: 100%;
		height: 32px;
		position: fixed;
		bottom: 190px;
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 4px;
	}

	.spot {

		background-color: #FFF;
		width: 10px;
		height: 10px;
		opacity: 0.3;
		border-radius: 10rpx;
	}


	.spot.active {
		opacity: 0.1;
		width: 30px;
		background-color: #000;
	}

	/* 单价首字大写 */
	.buy-price::first-letter {
		font-size: x-large;
	}

	.warn-address {
		border: 1px solid #dd524d;
	}

	.toSubmitReqsn {
		background: linear-gradient(135deg, $uni-color-success, $uni-color-banner);
	}
</style>